package cn.ljy.common.utils.password;

import java.util.Random;

/**
 * 验证码生成工具类
 */
public class VerificationCodeGenerator {

    private static final Random random = new Random();

    // 验证码类型常量
    public static final int TYPE_NUMERIC = 1;     // 纯数字
    public static final int TYPE_LETTER = 2;      // 纯字母
    public static final int TYPE_MIXED = 3;       // 数字+字母混合

    /**
     * 生成指定长度和类型的验证码
     * @param length 验证码长度
     * @param type 验证码类型：1-数字，2-字母，3-混合(NULL时默认为混合)
     * @return 验证码字符串
     */
    public static String generateCode(int length, Integer type) {
        if (length <= 0) {
            throw new IllegalArgumentException("验证码长度必须大于0");
        }

        // 默认为混合类型
        if (type == null) {
            type = TYPE_MIXED;
        }

        switch (type) {
            case TYPE_NUMERIC:
                return generateNumericCode(length);
            case TYPE_LETTER:
                return generateLetterCode(length);
            case TYPE_MIXED:
            default:
                return generateMixedCode(length);
        }
    }

    /**
     * 生成6位混合验证码（默认方法）
     * @return 6位验证码字符串
     */
    public static String generateCode() {
        return generateCode(6, TYPE_MIXED);
    }

    /**
     * 生成纯数字验证码
     * @param length 验证码长度
     * @return 数字验证码字符串
     */
    private static String generateNumericCode(int length) {
        StringBuilder code = new StringBuilder();
        code.append(random.nextInt(9) + 1); // 第一位为1-9

        for (int i = 1; i < length; i++) {
            code.append(random.nextInt(10)); // 每位为0-9
        }

        return code.toString();
    }

    /**
     * 生成纯字母验证码
     * @param length 验证码长度
     * @return 字母验证码字符串
     */
    private static String generateLetterCode(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder code = new StringBuilder();

        for (int i = 0; i < length; i++) {
            code.append(chars.charAt(random.nextInt(chars.length())));
        }

        return code.toString();
    }

    /**
     * 生成数字+字母混合验证码
     * @param length 验证码长度
     * @return 混合验证码字符串
     */
    private static String generateMixedCode(int length) {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder code = new StringBuilder();

        for (int i = 0; i < length; i++) {
            code.append(chars.charAt(random.nextInt(chars.length())));
        }

        return code.toString();
    }
}

